/* $RCSFile: MagicUrls.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/MagicUrls/MagicUrls.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:21  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:55  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:25  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.IO;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Globalization;

using AddonNice.UI.WebControls;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Core;
using AddonNice.Helpers;
using AddonNice.Configuration;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.PageModules.MagicUrls
{
	/// <summary>
	///	Manage url accelarators for the portal
	/// </summary>
	public partial class MagicUrls : PortalModuleControl
	{

		MagicUrlsDB magicDB	=	new MagicUrlsDB();

		/// <summary>
		/// General Module Def GUID
		/// </summary>
		public override Guid GuidID 
		{
			get
			{
				return new Guid("{345EB057-F35F-4882-A3F1-38A504A6C382}");
			}
		}

		/// <summary>
		/// Admin Module
		/// </summary>
		public override bool AdminModule
		{
			get
			{
				return true;
			}
		}
		/// <summary>
		/// Ctor
		/// </summary>
		public MagicUrls()
		{
			this.EnableViewState = true;
		}


		protected void Page_Load(object sender, EventArgs e)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MagicUrls Page_Load begin.",ModuleTraceSwitch.Sw.Info);
            string topText		= LocalizeHelper.Localize("MAGICURLS_TOPTEXT", "<b>MagicUrls</b> enables users to navigate to pages within a portal by appending just a number or a string to the base URL (like www.myportal.net/2291 or www.myportal.net/special). Numbers will always be interpreted automatically as a PageID. To use a string, enter it in the 'key' column and assign it to a PageID (e.g. 2291), an internal URL (e.g. ~/site/2291/special.aspx) or an external URL (e.g. http://www.microsoft.com) in the 'value' column. ");
			topText				= String.Format("<p>{0}</p>",topText);
			PlaceHolder1.Controls.Add(new LiteralControl(topText));
            string btmText		= LocalizeHelper.Localize("MAGICURLS_BTMTEXT", "NOTE: for this feature to work, you must assign a Custom Error in IIS - map 404 errors to '/AddonNice/app_support/MagicError.aspx' (assuming AddonNice is the name of your virtual directory).");
			btmText				= String.Format("<p>{0}</p>",btmText);
			PlaceHolder2.Controls.Add(new LiteralControl(btmText));
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MagicUrls Page_Load end.",ModuleTraceSwitch.Sw.Info);
		}

		/// <summary>
		/// Rebind the DataSet To DataTable
		/// </summary>
        void RadGrid1_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MagicUrls RadGrid1_NeedDataSource BEG.",ModuleTraceSwitch.Sw.Info);
            try
			{
				RadGrid1.DataSource = magicDB.GetMagicUrlsGlobalized(PortalID);
			}
			catch (Exception ex)
			{
				if ( PageTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MagicUrls RadGrid1_NeedDataSource ex: {0}", ex),PageTraceSwitch.Sw.Info);
                throw;
			}
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]MagicUrls RadGrid1_NeedDataSource END.",ModuleTraceSwitch.Sw.Info);
		}

		protected void RadGrid1_DeleteCommand(object source, GridCommandEventArgs e)
		{
            GridDataItem dataItem   =   (GridDataItem)e.Item;
            string modStr           =   dataItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ItemID"].ToString();
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicUrl RadGrid1_DeleteCommand Module: {0}", modStr),ModuleTraceSwitch.Sw.Info);
            try
            {
				magicDB.DeleteMagicUrlsGlobalized(int.Parse(modStr));
                RadGrid1.DataSource =   null;
                RadGrid1.Rebind();
            }
            catch (Exception ex)
            {
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MagicUrl RadGrid1_DeleteCommand Module: {0}, ex: {1}", modStr, ex),ModuleTraceSwitch.Sw.Info);
                throw;
            }
		}

		protected void RadGrid1_InsertCommand(object source, GridCommandEventArgs e)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]MagicUrl RadGrid1_InsertCommand BEG.",ModuleTraceSwitch.Sw.Info);

            GridEditableItem editedItem             =   e.Item as GridEditableItem;
            GridEditManager editMan                 =   editedItem.EditManager;

            string          newMagicKey             =   string.Empty;
            string          newMagicValue           =   string.Empty;
            string          newMagicComment         =   string.Empty;
            string          newMagicScheduleDay     =   string.Empty;
            string          newMagicScheduleHours   =   string.Empty;
            //Set new values
            foreach (GridColumn column in e.Item.OwnerTableView.RenderColumns)
            {
                if (column is IGridEditableColumn)
                {
                    IGridEditableColumn editableCol             =   (column as IGridEditableColumn);
                    if (editableCol.IsEditable)
                    {
                        IGridColumnEditor editor                =   editMan.GetColumnEditor(editableCol);

                        string editorText                       =   StStr.unknown;
                        string editorValue                      =   null;

                        if (editor is GridTextColumnEditor)
                        {
                            editorText                          =   (editor as GridTextColumnEditor).Text;
                            editorValue                         =   (editor as GridTextColumnEditor).Text;
                            try
                            {
                                switch(column.UniqueName)
                                {
                                    case "MagicKey":
                                        newMagicKey             =   editorValue;
                                        break;
                                    case "MagicValue":
                                        newMagicValue           =   editorValue;
                                        break;
                                    case "MagicComment":
                                        newMagicComment         =   editorValue;
                                        break;
                                    case "MagicScheduleDay":
                                        newMagicScheduleDay     =   editorValue;
                                        break;
                                    case "MagicScheduleHours":
                                        newMagicScheduleHours   =   editorValue;
                                        break;
                                }
                                if ( ModuleTraceSwitch.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicUrl RadGrid1_InsertCommand col: {0}, val: {1}.",column.UniqueName,editorValue),ModuleTraceSwitch.Sw.Info);
                            }
                            catch (Exception ex)
                            {
                                string msg  =   LocalizeHelper.Localize("MAGICURLS_INSERT_ERR","Unable to insert into MagicUrls.");
                                RadGrid1.Controls.Add(new LiteralControl( msg));
                                if ( ModuleTraceSwitch.Sw.TraceError )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MagicUrl RadGrid1_InsertCommand ex: {0}.",ex),ModuleTraceSwitch.Sw.Info);
                                e.Canceled = true;
                                return;
                            }
                        }

                    }
                }
            }
			try
			{
                if ( ModuleTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicUrl RadGrid1_InsertCommand add newMagicKey: {0}, newMagicValue: {1}, newMagicComment: {2}",
                        new object[]{newMagicKey,newMagicValue,newMagicComment}),
                        ModuleTraceSwitch.Sw.Info);
				magicDB.AddMagicUrls(PortalID,newMagicKey,newMagicValue,newMagicComment, 0, 0);
			}
			catch (Exception ex)
			{
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MagicUrl RadGrid1_InsertCommand ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
			}
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]MagicUrl RadGrid1_InsertCommand END.",ModuleTraceSwitch.Sw.Info);
        }

		protected void RadGrid1_UpdateCommand(object source, GridCommandEventArgs e)
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine("[V]MagicUrl RadGrid1_UpdateCommand BEG.",ModuleTraceSwitch.Sw.Info);
			GridEditableItem editedItem             =   e.Item as GridEditableItem;
			GridEditManager editMan                 =   editedItem.EditManager;
            
            int magicItemID                         =   (int)editedItem.GetDataKeyValue("ItemID");
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicUrl RadGrid1_UpdateCommand MagicItemID: {0}.",magicItemID),ModuleTraceSwitch.Sw.Info);
            string          newMagicKey             =   string.Empty;
            string          newMagicValue           =   string.Empty;
            string          newMagicComment         =   string.Empty;
            string          newMagicScheduleDay     =   string.Empty;
            string          newMagicScheduleHours   =   string.Empty;
            //Set new values
            foreach (GridColumn column in e.Item.OwnerTableView.RenderColumns)
            {
                if (column is IGridEditableColumn)
                {
                    IGridEditableColumn editableCol             =   (column as IGridEditableColumn);
                    if (editableCol.IsEditable)
                    {
                        IGridColumnEditor editor                =   editMan.GetColumnEditor(editableCol);

                        string editorText                       =   StStr.unknown;
                        string editorValue                      =   null;

                        if (editor is GridTextColumnEditor)
                        {
                            editorText                          =   (editor as GridTextColumnEditor).Text;
                            editorValue                         =   (editor as GridTextColumnEditor).Text;
                            try
                            {
                                switch(column.UniqueName)
                                {
                                    case "MagicKey":
                                        newMagicKey             =   editorValue;
                                        break;
                                    case "MagicValue":
                                        newMagicValue           =   editorValue;
                                        break;
                                    case "MagicComment":
                                        newMagicComment         =   editorValue;
                                        break;
                                    case "MagicScheduleDay":
                                        newMagicScheduleDay     =   editorValue;
                                        break;
                                    case "MagicScheduleHours":
                                        newMagicScheduleHours   =   editorValue;
                                        break;
                                }
                                if ( ModuleTraceSwitch.Sw.TraceVerbose )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicUrl RadGrid1_UpdateCommand col: {0}, val: {1}.",column.UniqueName,editorValue),ModuleTraceSwitch.Sw.Info);
                            }
                            catch (Exception ex)
                            {
                                if ( ModuleTraceSwitch.Sw.TraceError )
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MagicUrl RadGrid1_UpdateCommand ex: {0}.",ex),ModuleTraceSwitch.Sw.Info);
                                string msg  =   LocalizeHelper.Localize("MAGICURLS_UPDATE_ERR","Unable to update MagicUrls.");
                                RadGrid1.Controls.Add(new LiteralControl(msg));
                                e.Canceled = true;
                                return;
                            }
                        }

                    }
                }
            }
			try
			{
                if ( ModuleTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicUrl RadGrid1_UpdateCommand update newMagicKey: {0}, newMagicValue: {1}, newMagicComment: {2}",
                        new object[]{newMagicKey,newMagicValue,newMagicComment}),
                        ModuleTraceSwitch.Sw.Info);
				magicDB.UpdateMagicUrlsGlobalized(magicItemID,newMagicKey,newMagicValue,newMagicComment, 0, 0);
			}
			catch (Exception ex)
			{
                if ( ModuleTraceSwitch.Sw.TraceError )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MagicUrl RadGrid1_InsertCommand ex: {0}", ex),ModuleTraceSwitch.Sw.Info);
                throw;
			}
            if ( ModuleTraceSwitch.Sw.TraceError )
                Trace2.WriteLine("[V]MagicUrl RadGrid1_UpdateCommand END.",ModuleTraceSwitch.Sw.Info);
		}

		#region Std Overrides

		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}
		
		private void InitializeComponent()
		{
			Load					+=	new EventHandler(this.Page_Load);
            RadGrid1.UpdateCommand	+=  new GridCommandEventHandler(RadGrid1_UpdateCommand);
            RadGrid1.DeleteCommand  +=  new GridCommandEventHandler(RadGrid1_DeleteCommand);
			RadGrid1.InsertCommand	+=	new GridCommandEventHandler(RadGrid1_InsertCommand);
            RadGrid1.NeedDataSource +=  new GridNeedDataSourceEventHandler(RadGrid1_NeedDataSource);
		}
		#endregion

	}
}
